import hashlib
from urllib import request

from flask import Blueprint, jsonify, render_template, session, request, redirect, url_for

from utils.database_util import query_data
from utils.util import ArticleUtil
article_read = Blueprint('article_read', __name__)

# 新增函数以处理文章收藏逻辑


@article_read.route('/article_read')
def index():
    return  render_template("article_read.html")

def insert_favorite(article_id, user_id):
    # 检查该文章是否已经被该用户收藏
    sql = 'SELECT * FROM favorite WHERE article_id = %d AND user_id = %d' % (article_id, user_id)
    existing_favorite = query_data(sql)

    if existing_favorite:
        # 如果已经收藏，则更新收藏状态（假设有一个is_favorite字段）
        if not existing_favorite[0]['is_favorite']:
            sql = 'UPDATE favorite SET is_favorite = TRUE WHERE article_id = %d AND user_id = %d' % (
            article_id, user_id)
            query_data(sql)
            return "Article re-favorited."
        else:
            return "Article is already favorited."
    else:
        # 如果没有收藏，则插入新的收藏记录
        sql = 'INSERT INTO favorite (article_id, user_id, is_favorite, created_at, updated_at) VALUES (%d, %d, TRUE, NOW(), NOW())' % (
        article_id, user_id)
        query_data(sql)
        return "Article favorited."


@article_read.route('/article/list',methods=['GET','POST'])
def article_list():
    sql_str = "select article.*, users.nickname from article left join users on users.userid = article.userid order by updatetime desc limit 10"
    result = query_data(sql_str)
    result = ArticleUtil.transform_articles(result)
    if len(result):  #  有查询结果
        return jsonify({'code':1, 'info':result})
    else:  #  没有查询结果
        return jsonify({'code':0, 'info':[]})
@article_read.route('/article/list/<int:page>', methods=["GET","POST"])
def article_list_limit(page):
    number = 10
    result = query_data('select count(articleid) as `article_number` from article')
    count = result[0]['article_number']
    max_page = int(count / number) + 1
    start = (page - 1) * number
    end = start + number
    print("start", start)
    print("end", end)
    sql_str = "select article.*, users.nickname from article left join users on users.userid = article.userid order by updatetime desc limit %d,%d" % (start, end)
    print(sql_str)
    result = query_data(sql_str)
    result = ArticleUtil.transform_articles(result)
    if len(result):
        return jsonify({'code':1, 'info': result, 'page':{'max_page': max_page, 'now_page': page}})
    else:
        return jsonify({'code':0, 'info': []})

@article_read.route('/article/<int:article_id>', methods=["GET","POST"])
def article_info(article_id):
        sql = 'select * from article where articleid = %d' % article_id
        print("sql :", sql)
        result = query_data(sql)
        result = ArticleUtil.transform_articles(result)
        if len(result) == 0:
            return render_template("error-404.html")
        else:
            read_sql = 'update article set readcount = {} where articleid={}'.format(result[0]['readcount']+1, article_id)
            query_data(read_sql)
            userid = session.get('userid')
            if userid is None:
                return redirect(url_for('user_center.login'))
            user_sql = 'select * from users where userid = %d' % userid
            user_info = query_data(user_sql)
            user = user_info[0]
            number = user["credit"]-result[0]['credit']
            print("剩余积分数:", number)
            if number < 0:
                return render_template("home.html")
            credit_sql = 'update users set credit = {} where userid={}'.format(number, userid)
            query_data(credit_sql)
            return render_template("article_read.html", article=result[0])


def credit(user_id, article_id):
    sql = 'select credit from users where userid = %d' % user_id
    articles = query_data(sql)
    article = articles[0] if len(articles) == 1 else None
    if user_id != article['userid']:
        articles_credit = select_article_credit(article_id)
        user_credit = select_user_credit(user_id)
        if user_credit > articles_credit:
            if is_buy(user_id, article_id):
                return True
            update_user_credit(user_id, (user_credit - articles_credit), -articles_credit, "文章阅读扣除积分",
                               article_id)
            author_id = article['userid']
            author_credit = select_user_credit(author_id)
            update_user_credit(author_id, (author_credit + articles_credit), articles_credit, "文章被阅读增加积分",
                               article_id)
            return True
        else:
            return False
    else:
        return True


def select_user_credit(user_id):
    sql = 'select credit from users where userid = %d' % user_id
    user_info = query_data(sql)
    return user_info['credit']


def select_article_credit(article_id):
    sql = 'select credit from article where articleid = %d' % article_id
    articles = query_data(sql)
    return articles['credit']


def update_user_credit(user_id, credit, number, type, article_id):
    sql = 'update users set credit = {} where userid={}'.format(credit, user_id)
    query_data(sql)
    sql2 = 'INSERT INTO `credit` (`userid`, `category`, `target`, `credit`) VALUES (%d, %s, %d, %d)' % (
    user_id, type, article_id, number)
    query_data(sql2)
    print(user_id, ":", credit)


def is_buy(user_id, article_id):
    sql = 'select * from credit where userid = %d and target = %d' % (user_id, article_id)
    result = query_data(sql)
    return len(result) == 0
@article_read.route('/article/search/<int:page>', methods=["GET","POST"])
def article_search_limit(page):
    sql = 'select count(articleid) as `article_number` from article'
    select_sql = 'select article.*, users.nickname from article left join users on users.userid = article.userid order by updatetime desc limit {},{}'
    keyword = request.form.get("keyword")
    print(keyword)
    if keyword is not None:
        sql = 'select count(articleid) as `article_number` from article where headline like "%'+keyword+'%"'
        select_sql = 'select article.*, users.nickname from article left join users on users.userid = article.userid where headline like "%'+keyword+'%" order by updatetime desc limit {},{}'
    number = 10
    result = query_data(sql)
    count = result[0]['article_number']
    max_page = int(count / number) + 1
    start = (page - 1) * number
    end = start + number
    print("start", start)
    print("end", end)
    sql_str = select_sql.format(start, 10)
    print(sql_str)
    result = query_data(sql_str)
    result = ArticleUtil.transform_articles(result)
    if len(result):
        return jsonify({'code':1, 'info': result, 'page':{'max_page': max_page, 'now_page': page}})
    else:
        return jsonify({'code':0, 'info': []})

